﻿using LitJson;
using System.Collections.Generic;

namespace GameToolkit.ContentProvider
{
    public class TextRes : TableBase, TableBase.IOnSubmitTable, IMergeTableData
    {
        static readonly object _lock = new object();
        static List<TableSet<TextRes>> sList = new List<TableSet<TextRes>>();

        public string text { get; private set; }
        public string voice { get; private set; }
        protected override void OnDeserialize(JsonData data)
        {
            text = (string)data["text"];
            voice = (string)data["voice"];
        }

        public void MergeFrom(TableBase data)
        {
            var b = data as TextRes;
            if (b != null)
            {
                if (!string.IsNullOrEmpty(b.voice) && string.IsNullOrEmpty(voice))
                    voice = b.voice;
                if (!string.IsNullOrEmpty(b.text) && string.IsNullOrEmpty(text))
                    text = b.text;
            }
        }

        void IOnSubmitTable.OnSubmit(ITable table)
        {
#if UNITY_EDITOR
            if (table is TableSet<TextRes> tres && tres.IsEditorOnly)
                return;
#endif
            lock (_lock)
            {
                var tab = table as TableSet<TextRes>;
                if (tab != null && !sList.Contains(tab))
                    sList.Add(tab);
            }
        }

        void IOnSubmitTable.OnDispose(ITable table)
        {
            lock (_lock)
            {
                var tab = table as TableSet<TextRes>;
                if (tab != null)
                    sList.Remove(tab);
            }
        }

        public static void ReleaseAllTexts()
        {
            lock (_lock)
            {
                for (int i = sList.Count - 1; i >= 0; i--)
                {
                    sList[i].Dispose();
                }
                sList.Clear();
            }
        }

        public static TextRes GetText(int id, ITable exclude)
        {
            lock (_lock)
            {
                for (int i = 0; i < sList.Count; i++)
                {
                    var tab = sList[i];
                    if (tab == exclude)
                        continue;
                    var res = tab[id];
                    if (res != null)
                        return res;
                }
            }
            return null;
        }

        public static string GetVoice(int id, ITable exclude)
        {
            lock (_lock)
            {
                for (int i = 0; i < sList.Count; i++)
                {
                    var tab = sList[i];
                    if (tab == exclude)
                        continue;
                    var res = tab[id];
                    if (res != null && !string.IsNullOrEmpty(res.voice))
                        return res.voice;
                }
            }
            return null;
        }

    }
}
